<template>
  <div class="common-container">
    <div class="statistics" v-if="user.roleName == 'TENANT_ADMIN'">
      <div class="item" style="border-left: 8px solid #35a3f1">
        <div style="color: #35a3f1">{{ amountCount }}</div>
        <div>套餐包总量(条)</div>
      </div>
      <div class="item" style="border-left: 8px solid #fa9c95">
        <div style="color: #fa9c95">{{ usedCount }}</div>
        <div>套餐包已分配(条)</div>
      </div>
      <div class="item" style="border-left: 8px solid #8cdb7c">
        <div style="color: #8cdb7c">{{ remainCount }}</div>
        <div>套餐包余量(条)</div>
      </div>
    </div>

    <div class="div_box_content" :style="user.roleName != 'TENANT_ADMIN' ? 'height: calc(100% - 7px)' : ''
      ">
      <div class="header">
        <div class="header_left">
          <el-popover placement="bottom" width="460" trigger="click" popper-class="popover" size="small"
            v-model="showPopover">
            <div>
              <el-form label-width="70px" style="margin: 20px 0" class="popover_from">
                <el-form-item size="small" label="租户名称" v-if="user.roleName == 'PLATFORM_ADMIN'">
                  <el-select v-model="tenantId" filterable placeholder="请选择租户名称" size="small" v-loadMore="loadMore"
                    style="width: 360px;margin-left: 15px;" clearable @visible-change="enterprise">
                    <el-option v-for="(item, i) in enterpriseList" :key="i" :label="item.name" :value="item.id">
                    </el-option>
                    <div class="div_box" v-loading="loading" :style="loading ? '' : 'display: none;'"></div>
                  </el-select>
                </el-form-item>
                <el-form-item size="small" label="组织机构" v-if="user.roleName == 'TENANT_ADMIN'">
                  <TreeSearch style="width: 360px;margin-left: 15px;" @changeOrgId="changeOrgId" @onClear="onClear"
                    ref="refTreeSearch">
                  </TreeSearch>
                </el-form-item>
                <el-form-item size="small" label="联网单位" v-if="user.roleName == 'TENANT_ADMIN'">
                  <el-select size="small" style="width: 360px;margin-left: 15px;" clearable v-loadMore="loadMore2"
                    v-model='selectedValue' placeholder='请选择联网单位' filterable remote :remote-method="remoteMethod"
                    @clear="handleClear" v-if="user.roleName == 'TENANT_ADMIN'">
                    <el-option v-for='item in orgList' :label='item.orgName' :value='item.id' :key='item.id'>
                    </el-option>
                    <div class="div_box" v-loading="loading2" :style="loading2 ? '' : 'display: none;'"> </div>
                  </el-select>
                </el-form-item>
                <el-form-item size="small" label="状态">
                  <el-select v-model="state" placeholder="请选择状态" style="margin-left: 15px; width: 360px" size="small"
                    clearable>
                    <el-option v-for="item in stateList" :key="item.id" :label="item.type" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div class="footer" style="text-align: right">
                <el-button size="small" @click="resetClick" class="cancel-button">重 置</el-button>
                <el-button size="small" class="confirm-button" @click="onSearch">确 定</el-button>
              </div>
            </div>
            <el-button size="small" slot="reference" :class="hasSearch ? 'elhasSearch elhasSearch2' : 'elhasSearch2'">
              高级搜索<i class="el-icon-search" style="margin-left: 5px; font-size: 12px"></i></el-button>
          </el-popover>
        </div>

        <div class="header_right">
          <el-button size="small" icon="el-icon-plus" style="margin-left: 15px" @click="addClick"
            v-permission="{ action: 'voice:add' }">新增</el-button>
        </div>
      </div>
      <div class="content" :style="user.roleName == 'TENANT_ADMIN'
        ? 'height:calc(100% - 215px)'
        : 'height:calc(100% - 65px)'
        ">
        <el-table :data="dataList" height="calc(100% - 65px)" class="table" ref="refTable" row-key="id"
          :header-cell-style="headerStyle" v-loading="loadingTable" element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading" element-loading-background="rgba(47, 51, 73, 0.3)">
          <el-table-column align="center" label="序号" type="index" width="80">
          </el-table-column>

          <el-table-column align="center" prop="tenantName" label="租户名称" min-width="200" show-overflow-tooltip
            v-if="user.roleName == 'PLATFORM_ADMIN'">
          </el-table-column>

          <el-table-column align="center" prop="orgName" label="联网单位" min-width="200" show-overflow-tooltip
            v-if="user.roleName == 'TENANT_ADMIN'">
          </el-table-column>

          <el-table-column align="center" prop="amount" label="语音总量" min-width="130">
          </el-table-column>
          <el-table-column align="center" prop="used" :label="user.roleName == 'PLATFORM_ADMIN' ? '已分配' : '已使用条数'
            " min-width="130">
            <template slot-scope="scope">
              <el-tag type="danger" size="mini">{{
                scope.row.used
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remain" :label="user.roleName == 'PLATFORM_ADMIN' ? '未分配' : '剩余条数'
            " min-width="130">
            <template slot-scope="scope">
              <el-tag type="success" size="mini">{{
                scope.row.remain
              }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="state" label="是否有效" min-width="120">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.state == 1" type="success" size="mini">有效</el-tag>
              <el-tag v-if="scope.row.state == 2" type="danger" size="mini">已用完</el-tag>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="150">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="编辑" placement="bottom"
                v-permission="{ action: 'voice:edit' }">
                <i @click="editClick(scope.row)" class="iconfont tianxie tableBtnIcon"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="bottom"
                v-permission="{ action: 'voice:delete' }">
                <i @click="delClick(scope.row)" class="iconfont shanchu tableBtnIcon"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page.sync="page" :limit.sync="limit" :total="total" @pagination="PageMessagePackage"
          class="pagination">
        </pagination>
      </div>
    </div>
    <addServiceVoice ref="refAdd" :targetId="targetId"></addServiceVoice>
    <editServiceVoice ref="refEdit" :editData="editData"></editServiceVoice>
  </div>
</template>

<script>
import {
  reqPageVoicePackage,
  reqVoicePackageRemove,
  reqVoicePackage,
  reqTenantList,
  reqOrgList,
} from "@api/api.js";
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { mapState } from "vuex";
import addServiceVoice from "./components/addServiceVoice.vue";
import editServiceVoice from "./components/editServiceVoice.vue";
import loadMore from "@mixin/loadMore";
import TreeSearch from "@components/TreeSearch.vue";

export default {
  name: "voice",
  components: {
    Pagination,
    addServiceVoice,
    editServiceVoice,
    TreeSearch
  },
  mixins: [tableStyleMixin, loadMore],
  data() {
    return {
      // 今日统计
      isolationPersonTodayCount: {
        inIsolation: 0,
        sumIsolation: 0,
        disIsolation: 0,
      },
      // 昨日统计
      isolationPersonYesterdayCount: {
        inIsolation: 0,
        sumIsolation: 0,
        disIsolation: 0,
      },
      dataList: [],
      loadingTable: false,
      page: 1,
      limit: 10,
      total: 0,
      orgId: "",

      // 有效/已用完
      stateList: [
        { id: "1", type: "有效" },
        { id: "2", type: "已用完" },
      ],
      tenantId: "",

      loadingSearch: false,
      editData: {}, //编辑数据
      batchDataList: [], //批量操作勾选的数据
      state: "",

      // 统计
      amountCount: 0,
      remainCount: 0,
      usedCount: 0,

      enterpriseList: [],
      orgList: [],
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,
      flag: true,
      flag2: true,
      loading: false,
      loading2: false,
      sysInstanceIndex2: 1,
      sysInstanceTotalPages2: 10,
      orgName: "",
      selectedValue: "",
      targetId: "",
      hasSearch: false,
      showPopover: false,
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  mounted() {
    if (this.user.roleName == "TENANT_ADMIN") {
      this.selectedValue = this.spacesManage.organizationInfo.orgId;
      this.MessagePackage(); //获取租户短信包
    } else {
      // this.PageMessagePackage(); // 短信包列表
    }
    this.PageMessagePackage(); // 短信包列表
  },
  activated() {
    if (this.user.roleName == "TENANT_ADMIN") {
      this.selectedValue = this.spacesManage.organizationInfo.orgId;
      this.MessagePackage(); //获取租户短信包
    } else {
      // this.PageMessagePackage(); // 短信包列表
    }
    this.PageMessagePackage(); // 短信包列表
  },
  methods: {
    // 搜索
    async onSearch() {
      this.showPopover = false;
      this.page = 1;
      this.limit = 10;
      await this.PageMessagePackage();
    },
    // 高级搜索重置
    async resetClick() {
      this.state = ''
      this.tenantId = ''
      this.parentId = ''
      this.selectedValue = ''
      if (this.user.roleName != 'INSTERALL_USER' && this.user.roleName != 'UNIT_ADMIN') {
        this.orgList = []
      }
      if (this.$refs.refTreeSearch) {
        this.$refs.refTreeSearch.onclose()
      }
      this.page = 1;
      this.limit = 10;
      await this.PageMessagePackage();
    },
    changeOrgId(instanceId) {
      this.parentId = instanceId.id
      this.handleClear();
    },
    onClear() {
      // this.targetId = this.spacesManage.organizationInfo.orgId;
      // this.page = 1;
      // this.limit = 10;
      // this.PageMessagePackage();
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      // 获取列表数据的方法
      await this.getEnterpriseList();
      this.loading = false;
    },
    enterprise(val) {
      if (val && this.flag) {
        this.getEnterpriseList();
        this.flag = false; //只执行一次
      }
    },
    // 获取租户列表
    async getEnterpriseList() {
      var res = await reqTenantList(this.sysInstanceIndex, 10);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages = res.data.total;
      this.enterpriseList = [...this.enterpriseList, ...res.data.rows];
      // res.data.rows.forEach((e) => {
      //   this.enterpriseList.push({ id: e.id, name: e.name });
      // });
    },
    // 清空
    handleClear() {
      this.selectedValue = "";
      this.orgName = "";
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.orgList = [];
      this.getOrgList();
    },
    // 远程搜索
    async remoteMethod(query) {
      this.selectedValue = query; //保留输入的值
      this.orgName = query;
      this.sysInstanceIndex2 = 1;
      this.sysInstanceTotalPages2 = 10;
      this.orgList = [];
      this.getOrgList();
    },
    async loadMore2() {
      if (this.sysInstanceIndex2 >= Math.ceil(this.sysInstanceTotalPages2 / 10))
        return;
      this.sysInstanceIndex2++;
      this.loading2 = true;
      // 获取列表数据的方法
      await this.getOrgList();
      this.loading2 = false;
    },
    // // 下拉请求列表
    // enterpriseChange(val) {
    //   if (val && this.flag2) {
    //     this.getOrgList();
    //     this.flag2 = false; //只执行一次
    //   }
    // },
    // 获取单位列表
    async getOrgList() {
      var res = await reqOrgList({
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        orgName: this.orgName,
        parentId: this.parentId,
        type: "4"
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      // let { rows } = res.data;
      // this.orgList = rows;
      this.orgList = res.data.rows
    },
    clearStateList() {
      this.page = 1;
      this.limit = 10;
      this.PageMessagePackage();
    },
    //获取租户短信包
    async MessagePackage() {
      const res = await reqVoicePackage(this.user.tenantId);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.amountCount = res.data.row.amount || 0;
      this.remainCount = res.data.row.remain || 0;
      this.usedCount = res.data.row.used || 0;
    },
    // 短信包列表
    async PageMessagePackage() {
      if (this.user.roleName == "TENANT_ADMIN") {
        this.tenantId = this.user.tenantId;
      }
      this.loadingTable = true;
      const res = await reqPageVoicePackage(this.page, this.limit, {
        tenantId: this.tenantId,
        orgId: this.selectedValue == '' ? this.parentId : this.selectedValue,//机构||单位
        state: this.state,
        roleName: this.user.roleName,
      });
      this.loadingTable = false;
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      if (this.user.roleName == "TENANT_ADMIN") {
        this.hasSearch = (this.state || this.parentId || this.selectedValue) ? true : false
      } else {
        this.hasSearch = (this.tenantId || this.state) ? true : false
      }
      this.dataList = res.data.rows;
      this.total = res.data.total;
    },
    // 搜索
    async searchClick() {
      this.page = 1;
      this.limit = 10;
      this.loadingSearch = true;
      await this.PageMessagePackage();
      this.loadingSearch = false;
    },
    // 新增
    addClick() {
      this.$refs.refAdd.dialogVisible = true;
      if (this.user.roleName == "PLATFORM_ADMIN") {
        this.$refs.refAdd.getEnterpriseList();
      } else {
        this.$refs.refAdd.getOrgList();
      }
    },
    // 编辑
    editClick(row) {
      this.editData = JSON.parse(JSON.stringify(row));
      this.$refs.refEdit.dialogVisible = true;
    },
    // 删除
    async delClick(row) {
      const result = await this.$confirm(
        `此操作将删除该短信包, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => { });
      if (result !== "confirm") return;
      let params = {
        data: {
          id: row.id,
          roleName: this.user.roleName,
        },
      };
      const res = await reqVoicePackageRemove(params);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除短信包成功");
      this.PageMessagePackage();
      if (this.user.roleName == "TENANT_ADMIN") {
        this.MessagePackage(); //更新统计
      }
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("~@views/style/tree.less"); //左侧组织机构样式

.common-container {
  box-shadow: none !important;

  // background-color: transparent;
  .header {
    background-color: @primaryHeaderBgcolor;
    border-radius: 6px 6px 0 0;
    position: relative;
  }
}

.statistics {
  position: relative;
  // border-radius: 6px;
  // height: 20%;
  min-height: 130px;
  width: 100%;
  // margin-bottom: 18px;
  color: @primaryThemeTxtColor;
  display: flex;
  justify-content: space-between;
  padding: 1% 2% 1% 2%;
  box-sizing: border-box;
  border-bottom: 1px solid @primaryBorderColor;
  background: @primaryBgcolor;
  z-index: 9;

  .item {
    box-sizing: border-box;
    // border-radius: 6px;
    width: 31%;
    background: @primarywarn;
    // box-shadow: 0 4px 24px 0 ~"rgb(34 41 47 / 10%)";
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    >div:first-of-type {
      font-size: 40px;
      font-weight: 700;
      font-family: electronicFont;
    }

    >div:last-of-type {
      font-size: 16px;
      color: #aaa;
    }
  }
}

.popover_footer {
  width: 100%;
  display: flex;
  justify-content: center;
}

.content {
  height: calc(100% - 61px) !important;
}

::v-deep .el-button--small {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 下拉框加载开始
.div_box {
  height: 276px;
  position: absolute;
  top: -1px;
  left: -1px;
  width: 190px;
  z-index: 9999;
}

::v-deep .el-loading-mask {
  border-radius: 4px;
}

// 下拉框加载结束

.div_box_content {
  height: calc(100% - 135px);
  // box-shadow: @boxShadow;
}

// 高级搜索
::v-deep .el-button--primary {
  background-color: #7367f0;
  border: 1px solid #7367f0;
  color: #fff;
}

::v-deep .el-form-item__label {
  color: @primaryThemeTxtColor2 ;
  padding: 0px;
}

::v-deep .el-input__inner {
  color: var(--primaryContentTxt, #f1f1f1);
}

.dropdown {
  background: #7367f0;
  color: #fff;
  border: none;
}

// 高级搜索----------</style>